package com.alageek.gulimall.product.service.impl;

import com.alageek.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.alageek.common.utils.PageUtils;
import com.alageek.common.utils.Query;

import com.alageek.gulimall.product.dao.CategoryDao;
import com.alageek.gulimall.product.entity.CategoryEntity;
import com.alageek.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> allCategories = baseMapper.selectList(null);
        return allCategories.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .peek(categoryEntity -> categoryEntity.setChildren(getChildren(categoryEntity, allCategories)))
                .sorted(Comparator.comparingInt(categoryEntity -> (categoryEntity.getSort() == null ? 0 : categoryEntity.getSort())))
                .collect(Collectors.toList());
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO 检查当前删除的菜单是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> list = new ArrayList<>();
        while (catelogId != 0) {
            list.add(catelogId);
            CategoryEntity categoryEntity = this.getById(catelogId);
            catelogId = categoryEntity.getParentCid();
        }
        int length = list.size();
        Long[] path = new Long[length];
        for (int i = 0; i < length; i++) {
            path[i] = list.get(length - i - 1);
        }
        return path;
    }

    @Transactional
    @Override
    public void updateDetail(CategoryEntity category) {
        // 保证冗余字段数据一致
        updateById(category);
        if(StringUtils.hasText(category.getName())){
            // 同步更新其他关联表中的数据
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
            // TODO 更新其他关联表
        }
    }

    // 递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildren(CategoryEntity parent, List<CategoryEntity> allCategories) {
        return allCategories.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(parent.getCatId()))
                .peek(categoryEntity -> categoryEntity.setChildren(getChildren(categoryEntity, allCategories)))
                .sorted(Comparator.comparingInt(categoryEntity -> (categoryEntity.getSort() == null ? 0 : categoryEntity.getSort())))
                .collect(Collectors.toList());
    }

}